package de.slothsoft.wasbinich.swingclient.database;

import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.LoginBean;
import de.slothsoft.wasbinich.core.database.webservice.AbstractOAuth2Authenticator.Token;
import de.slothsoft.wasbinich.core.database.webservice.RestCommunicator;
import de.slothsoft.wasbinich.swingclient.GlobalEventScopes;
import de.slothsoft.wasbinich.swingclient.common.GlobalEvent;
import de.slothsoft.wasbinich.swingclient.common.GlobalEventHandler;

public class SwingLoginBean implements LoginBean {

    private final SwingOAuth2Authenticator authenticator;
    private Token token;

    public SwingLoginBean(RestCommunicator restCommunicator) {
	this.authenticator = new SwingOAuth2Authenticator(restCommunicator);
    }

    @Override
    public void logOut() {
	this.token = null;
	this.authenticator.invalidateToken();
	GlobalEventHandler.getGlobalInstance().fireEvent(new GlobalEvent(this, GlobalEventScopes.LOG_OUT, null));
    }

    @Override
    public boolean isLoggedIn() {
	return this.token != null;
    }

    @Override
    public synchronized String getLoginToken() throws DatabaseException {
	this.token = this.authenticator.getToken();
	if (this.token != null) {
	    System.out.println("Using token: " + this.token.accessToken + ", expiring " + this.token.expireDate);
	    GlobalEventHandler.getGlobalInstance().fireEvent(
		    new GlobalEvent(this, GlobalEventScopes.LOG_IN, this.authenticator.getAuthenticatedUser()
			    .getLogin()));
	}
	return this.token == null ? null : this.token.accessToken;
    }

}
